var _ = require('lodash');

const Utils = {};

Utils.paramerUrl = () => {
    // 解决乱码问题
    var url = decodeURI(window.location.href)
    var res = {}
    var url_data = _.split(url, '?').length > 1 ? _.split(url, '?')[1] : null ;
    if (!url_data) return null
    var params_arr = _.split(url_data, '&')
    _.forEach(params_arr, function(item) {
        var key = _.split(item, '=')[0]
        var value = _.split(item, '=')[1]
        res[key] = value
    });
    return res
}

// 防抖
Utils.debounce = function(methods, delay = 80, immediate = false) {
    let timer;
    let firstisOK = false;

    return function () {
        let args = arguments;
        timer && clearTimeout(timer);
        if(immediate && !firstisOK) {
            methods.apply(this, args);
            firstisOK = true;
        }
        timer = setTimeout(function() {
            methods.apply(this, args);
            firstisOK = false;
        }, delay);
    }
}

// 节流
Utils.throttle = function (method, wait = 50) {
    let timer,
        startTime;

    return function loop() {
        var self = this;
        var args = arguments;
        if (!startTime) {
            startTime = Date.now();
        }

        timer && clearTimeout(timer);

        if (Date.now() - startTime > wait) {
            method.apply(self, args);
            startTime = Date.now();
        } else {
            timer = setTimeout(function() {
                method.apply(self, args);
            }, wait)
        }
    }
}

export  default Utils
